<?php
namespace app\admin\validate;

use think\Validate;
use think\Db;
use think\Input;
class User extends Validate
{
	protected $rule = [
	'username'  => 'require|checkHasValue:username|alphaNum|max:25',
	'password'  => 'require|min:6',
	'email'     => 'require|email|checkHasValue:email',
	]; 

	protected $message  =   [
        'username.require'                => '用户名不能为空',
        'username.checkHasValue:username' => '用户名已存在',
        'username.alphaNum'               => '用户名必须是字母、数字', 
        'username.max'					  => '用户名最大长度为25',
        
        'email.email'                     => '请输入正确的邮箱',
        'email.checkHasValue:email'       => '邮箱已存在',
        
        'password.require'                => '请输入密码',
        'password.min'                    => '密码最短为6位',
    ];

    protected $scene = [
        'edit'                 =>  ['email'],
        'add'                  =>  ['username','password','email'],
    ];


	protected function checkHasValue($value,$rule) {      
		switch ($rule) {
			case 'username': 
				$hasValue = Db::name('User')->where('username',$value)->find();
				if (empty($hasValue)) {
					return true;
				} else {
					return '用户名已存在';
				}
				break; 
			case 'email':
				$id = input('id');
				if (empty($id)) {
					$hasValue = Db::name('User')->where('email',$value)->find();
					if (empty($hasValue)) {
						return true;
					} else {
						return "邮箱已存在！";
					}
				} else {
				//更改资料判断邮箱是否与其他人的邮箱相同
					$checkValue = Db::name('User')
						->where('id','neq',$id)
						->where('email',$value)
						->find();
					if (empty($checkValue)) {
						return true;
					} else {
						return "邮箱已存在";
					}
				}
				break;           
			default:
			# code...
			break;
		}          
	}
}


